/**
 * @Title: settleAnalyseMain_ctrl.js
 * @Description: TODO
 * Copyright: Copyright (c) 2014 
 * Company:中国平安
 *
 * @Project HIMS-FWA
 * @author QIANDUO875
 * @date 2014年9月26日 上午10:32:01
 * @version V1.0
 */
;
(function(){
	'use strict';
	
	var app = angular.module('fwa.mainApp');
	app.controller('SettleAnalyseMainCtrl',
			['$scope','$state','SettleAnalyseService','$stateParams' ,'SettleAnalyseDepartService','Modal','CommunityService',
	          function($scope,$state,SettleAnalyseService,$stateParams,SettleAnalyseDepartService,Modal,CommunityService){
		
		/*********************************************************
		 * 
		 * Scope & Variables Init
		 * 
		 */
		$scope.communityService = CommunityService;
    	
    	CommunityService.initCodeListDatas();
    	SettleAnalyseService.initMedicalOrgInfoList();
    	$scope.settleAnalyseService = SettleAnalyseService;
    	//查询机构
    	function initQuery() {
    		var orgLevels = $scope.query.orgLevel;
    		var orgTypes = $scope.query.orgCategory;
    		//清空选中的值
    		$scope.query.org = '';
			$scope.query.depart = null;
//			$scope.query.doctor = '';
			SettleAnalyseService.initMedicalOrgInfoList(orgTypes,orgLevels);
    	}
    	$scope.orgCategory = false;
    	$scope.orgLevel = false;
    	//判断如果是第一次加载则不执行
    	var isLevels = false;
    	var isTypes = false;
    	//监听修改机构级别
    	$scope.$watch('query.orgLevel',function(v){
			if(v){
				isLevels = true;
    			$scope.orgCategory = true;
    		}else{
    			$scope.orgCategory = false;
    		}
    		if (isLevels) {
    			initQuery();
    		}
		});
    	
    	//监听修改机构类型
    	$scope.$watch('query.orgCategory',function(v){
    		if(v){
    			isTypes = true;
    			$scope.orgLevel = true;
    			
    		}else{
    			$scope.orgLevel = false;
    		}
    		if (isTypes) {
    			initQuery();
    		}
    		
		});
    	var isOrg = false;
    	//监听医疗机构修改
    	$scope.$watch('query.org',function(v){
    		
    		if ($state.current.name != Dept_View) {
    			isOrg = true;
    		}
    		
    		if (isOrg) {
    			$scope.query.depart = null;
    		}
    		isOrg = true;
    		
			if (v) {
				SettleAnalyseService.initMedicalDeptInfoList(v,false);
			}
			else {
				//清空科室和医生
				$scope.settleAnalyseService.medicalDeptInfoList = [];
//				$scope.query.doctor = '';
			}
		});
    	
    	
    	$scope.orgLevelDatas = [];
    	//监听医疗机构修改
    	$scope.$watch('communityService.orgLevelDatas',function(v){
			if(v){
				angular.forEach(v,function(data,index){
					if (data.code != '6') {
						$scope.orgLevelDatas.push(data);
					}
				});
			}
		});
    	
		var Region_View = 'settleAnalyse.regionView',
			Org_View = 'settleAnalyse.orgView',
			Dept_View = 'settleAnalyse.departView';
		
		var indicator = $stateParams.indicator;
		var view = $stateParams.view;
		
		var searchTemplMap = {};
		
		var orgChanged = false,
			deptChanged = false;
		
		$scope.orgSelected = null;
		$scope.doctorSelected = null;
		
		//表格标题
		var headers = [
		     		    {label: '1月', name: 'first'},
		     		    {label: '2月', name: 'second'},
		     		    {label: '3月', name: 'third'},
		     		    {label: '4月', name: 'fourth'},
		     		    {label: '5月', name: 'fifth'},
		     		    {label: '6月', name: 'sixth'},
		     		    {label: '7月', name: 'seventh'},
		     		    {label: '8月', name: 'eighth'},
		     		    {label: '9月', name: 'ninth'},
		     		    {label: '10月', name: 'tenth'},
		     		    {label: '11月', name: 'eleventh'},
		     		    {label: '12月', name: 'twelfth'}
		     	    ];
		//页面上展示的表格标题
		$scope.headers = [{label:'名称',name:'name'},
		        		    {label:'同比', name:'yoy'},
		          		    {label:'环比', name:'mom'}];
		
		//根据表头日期显示日期下的数据
		$scope.tableDataNames = [];
		
		$scope.$parent.query = {
			indicators:["KPI0001","KPI0003","KPI0004","KPI0013","KPI0007"],    //需要计算以万为单位的指标
    		indicator:indicator,
    		view:view
    	};
		
		
		$scope.serv = SettleAnalyseService;
		
		//echarts 横坐标显示值
		$scope.query.data = [];
		
		/*********************************************************
		 * 
		 * private function  判断需要展示的搜索条件
		 * 
		 */
		function fillSearchTemplMap() {
			if(indicator === 'budget') {
				searchTemplMap[Region_View] = 'regionView_search_templ2';
				searchTemplMap[Org_View] = 'regionView_search_templ2';
				searchTemplMap[Dept_View] = 'regionView_search_templ2';
			} 
			
			else if(indicator === 'pfound') {
				searchTemplMap[Region_View] = 'regionView_search_templ3';
				searchTemplMap[Org_View] = 'regionView_search_templ3';
				searchTemplMap[Dept_View] = 'regionView_search_templ3';
			}
			
			else {
				searchTemplMap[Region_View] = 'regionView_search_templ';
				searchTemplMap[Org_View] = 'orgView_search_templ';
				searchTemplMap[Dept_View] = 'orgView_search_templ';
			}
			if(view == 'org'){
				searchTemplMap[Org_View] = 'regionView_search_templ4';
				searchTemplMap[Dept_View] = 'regionView_search_templ4';
			}
		}
		
		//根据选中的日期调整表格标题以及echarts显示的日期
		function generateHeaderByDate() {
			if(!$scope.query.date) {
				return;
			}
			var start = $scope.query.date.start;
			var end = $scope.query.date.end;
			var startMonth = parseInt(start.substring(5,7)),
				endMonth = parseInt(end.substring(5,7)),
				startYear = parseInt(start.substring(0,4)),
				endYear = parseInt(end.substring(0,4));
			if((endYear-startYear)*12 + (endMonth-startMonth) >12) {
				return;
			}
			
			var tmpHeaders = [{label:'名称',name:'name'}];
			var array=new Array();
			$scope.tableDataNames = [];
			for(var m = startMonth; m<= endMonth + (endYear-startYear)*12; m++) {
				var idx = m%12;
				idx = idx == 0?12:idx;
				
				array.push(idx);
				$scope.query.data.push(headers[idx-1].label);
				$scope.tableDataNames.push(headers[idx-1].name);
				tmpHeaders.push(headers[idx-1]);
			}
			tmpHeaders = tmpHeaders.concat([{label:'同比', name:'yoy'},
			                      		    {label:'环比', name:'mom'}]);
			$scope.headers = tmpHeaders;
			
		}
		
		//跳转
		function stateSkip() {
			isQuery = true;
			if($state.current.name === Region_View) {
				if ($scope.query.depart) {
					if(!$scope.query.org) {
						Modal.alert('必须选择机构!');
						return;
					}
					isQuery = false;
					$state.go(Dept_View,{
						orgCode:$scope.query.org ,
						doctor:$scope.query.doctor,
						id:$scope.query.depart||''
					});
					
				}
				else  if ($scope.query.org) {
					isQuery = false;
					$state.go(Org_View,{
						id:$scope.query.org,
						dept:$scope.query.depart||''
					});
					
				}
			}
			
			else if($state.current.name === Org_View) {
				if ($scope.query.depart) {
					if(!$scope.query.org) {
						Modal.alert('必须选择机构!');
						return;
					}
					isQuery = false;
					$state.go(Dept_View,{
						orgCode:$scope.query.org ,
						doctor:$scope.query.doctor,
						id:$scope.query.depart ||''
					});
					
				}
				else if ($scope.query.org) {
					isQuery = false;
					$state.go(Org_View,{
						id:$scope.query.org,
						dept:$scope.query.depart ||''
					});
				}
				else {
					isQuery = false;
					$state.go(Region_View);
				}
			}
			
			else if($state.current.name === Dept_View) {
				if($scope.query.depart) {
					if(!$scope.query.org) {
						Modal.alert('必须选择机构!');
						return;
					}
					isQuery = false;
					$state.go(Dept_View,{
						orgCode:$scope.query.org ,
						doctor:$scope.query.doctor,
						id:$scope.query.depart ||''
					});
				}
				else if($scope.query.org) {
					isQuery = false;
					$state.go(Org_View,{
						id:$scope.query.org,
						dept:$scope.query.depart ||''
					});
				}
				else {
					isQuery = false;
					$state.go(Region_View);
				}
			}
		}
		
		//初始化
		function init(stateName, params) {
			$scope.searchTempl = searchTemplMap[stateName];
			SettleAnalyseService.checkedArray = [];
			SettleAnalyseService.typeSelected = '';
			
			SettleAnalyseService.getIndicatorInfo($stateParams.indicator).
				success(function(res){
					$scope.indicator = res;
					if($scope.indicator.type == 1) {
						$scope.serv.typeSelected = 'hosp';
					} else if($scope.indicator.type == 2){
						$scope.serv.typeSelected = 'out';
					} else {
						$scope.serv.typeSelected = 'all';
					}
				});
			SettleAnalyseService.view = stateName;
		}
		
		/*********************************************************
		 * 
		 * Event Handler
		 * 
		 */
		//是否需要向下抛出查询事件
		var isQuery = true;
		//查询
		$scope.onSubmit = function(){
			//判断日期跨度不能大于一年
			var checkTemp = CommunityService.checkDateSpan($scope.query.date.start,$scope.query.date.end);
			if(checkTemp!=''&&checkTemp.length>0){
				Modal.alert(checkTemp);
				return false;
			}
			//清空选中的值
			SettleAnalyseService.checkedArray = [];
			$scope.query.data = [];
			stateSkip();
			
			generateHeaderByDate();
			if (isQuery) {
				$scope.$broadcast('settleAnalyse.searchQuery');
			}
			
		}
		//重置
		$scope.onReset = function() {
			resetNull();
			$scope.query.data = [];
			$scope.query.date = {
					start: startDate,
					end:endDate
			};
			stateSkip();
			generateHeaderByDate();
//			$scope.$broadcast('settleAnalyse.searchReset');
		}
		//总，住 ，门 切换
		$scope.typeClick = function(type) {
			//打开 loading遮罩层
			SettleAnalyseService.loading = true;
			$scope.serv.typeSelected = type;
			$scope.$broadcast('settleAnalyse.dataTypeChange', type);
		}
		//清空选中的值 
		function resetNull() {
			$scope.query.org = '';
			$scope.query.doctor = '';
			$scope.query.depart = null;
			$scope.query.orgLevel = null;
			$scope.query.orgCategory = null;
			$scope.query.visit = '';
			$scope.orgSelected = null;
			$scope.departs = '';
		}
		/*********************************************************
		 * 
		 * Init
		 * 
		 */
		//跳转路由监听
		$scope.$on('$stateChangeSuccess', function(event , toState, toParams, fromState){
			if(toState.name && toState.name.indexOf('settleAnalyse.') == -1
					&& toState.name != 'settleAnalyse') {
				return;
			}
			SettleAnalyseService.checkedArray = [];
			if(toState.name == Region_View) {
				resetNull();
			}
			else if(toState.name == Org_View) {
				$scope.query.doctor = '';
			}
			$scope.searchTempl = searchTemplMap[toState.name];
			
			SettleAnalyseService.view = toState.name;
		});
		
		fillSearchTemplMap();
		
		init($state.current.name, $stateParams);
		
		//根据传过来的日期 
		var startDate = $stateParams.startDate ;
		var endDate = $stateParams.endDate;
		$scope.query.date = {};
		//结束日期
		if (!endDate 
			|| endDate == ''
			|| endDate == null) {
			//默认日期 当前日期的前一个月
			CommunityService.initDate("yyyy-MM").success(function(res) {
				endDate = CommunityService.lastMonth(res.formatDate);
				startDate = CommunityService.lastYear(endDate);
				$scope.query.date = {
						start: startDate,
						end:endDate
				};
				generateHeaderByDate();
			});
		}
		else {
			//开始日期
			if (!startDate 
				|| startDate == ''
				|| startDate == null) {
				startDate = CommunityService.lastYear(endDate);
			}
			
			$scope.query.date = {
					start: startDate,
					end:endDate
			};
			generateHeaderByDate();
		}
		
		if($state.current.name === 'settleAnalyse') {
			$state.go(Region_View);
			return;
		}
	}]);
	
})();